#include "EntHandler.h"
#include <algorithm>

EntHandler::EntHandler(World* w) {
	list.clear();
	world = w;
}

EntHandler::~EntHandler() {
	while (list.size()>1) {
		remove(list[0]);
	}
}

void EntHandler::add(Ent* _e) {
	// assert(_e->handler == NULL);
	list.push_back(_e);
	_e->handler = this;
}

void EntHandler::remove(Ent* _e) {
	list.erase(std::find(list.begin(), list.end(), _e));
	delete _e;
}

void EntHandler::setName(Ent* e, std::string n) {
	names.erase(n);
	names.insert(std::pair<std::string, Ent*>(n,e));
}

std::string EntHandler::getName(Ent* e) {
	std::map<std::string, Ent*>::iterator it;
	for (it = names.begin(); it != names.end(); ++it) {
		if ((*it).second == e)
			return (*it).first;
	}
	return ""; // not found
}

Ent* EntHandler::find(std::string name) {
	std::map<std::string, Ent*>::iterator it;
	it = names.find(name);
	if (it == names.end()) {
		return 0; // NULL
	}
	return (*it).second;
}

void EntHandler::thinkAll() {
	for (std::vector<Ent*>::iterator it = list.begin(); it != list.end(); ++it)
		(*it)->think();
}

void EntHandler::drawAll() {
	for (std::vector<Ent*>::iterator it = list.begin(); it != list.end(); ++it) {
		glPushMatrix();
		vect pos = (*it)->getPosition();
		glTranslated(pos.x, pos.y, pos.z);
		(*it)->draw();
		glPopMatrix();
	}
}

World* EntHandler::getWorld() {
	return world;
}
